package com.teama4.shop.controller;

import com.teama4.shop.domain.User;
import com.teama4.shop.service.UserService;
import com.teama4.shop.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;

    private String filePath = "/myFile/img/userHeadPic";

    @GetMapping("/findUser")
    public String findUser(@RequestParam("id") int id, Model model) {
        User user = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "修改用户");
        return "/admin/user-add";
    }

    @GetMapping("/merchantMessageUpdate")
    public String merchantMessageUpdate(@RequestParam("id") int id, Model model) {
        User user = userService.selectByPrimaryKey(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "用户信息修改");
        return "/merchant/merchant-message-update";
    }

    @GetMapping("/goToAddPage")
    public String goToAddPage(Model model){
        User user = new User();
        user.setHead("init_head.jpg");
        model.addAttribute("user", user);
        model.addAttribute("title", "增加用户");
        return "/admin/user-add";
    }

    @PostMapping("/addUser")
    public String addUser(User user, MultipartFile file) throws IOException {
        picCreat(user, file);
        userService.saveUser(user);
        return "redirect:/index/userList";
    }

    @PostMapping("/updateMerchant")
    public String updateMerchant(User user, MultipartFile file) throws IOException {
        picCreat(user, file);
        userService.updatePartByPrimaryKey(user);
        return "redirect:/index/merchantStoreList?id=" + user.getId();
    }

    private void picCreat(User user, MultipartFile file) throws IOException {
        if(!file.isEmpty()) {
            String filename = file.getOriginalFilename();
            String sname = filename.substring(filename.lastIndexOf("."));
            String name = UUID.randomUUID() + sname;
            user.setHead(name);
            FileUtil.dictionary_add(file, filePath, name);
        }
    }

    @DeleteMapping("/deleteUser")
    @ResponseBody
    public Boolean deleteUser(@RequestParam("id") int id) {
        int deleted = userService.deleteByPrimaryKey(id);
        return deleted > 0;
    }


}
